# coding:utf-8
__time__ = '2022/5/16 15:01'
__author__ = 'vantong'

import pymysql
import requests
import json

import pymysql
import datetime

def dingtalk_warning(message):
    """
    这个方法是定义钉钉发送告警信息
    :param message: 是传入的需要发送的信息，是个列表
    :return:
    """
    if len(message) == 0:
        pass
    else:
        # 测试群
        webhook = "xxxxx"
        # 正式群
        # webhook = "xxxxxxxx"
        headers = {
            "Content-Type": "application/json",
            "Chartset": "utf-8"
        }
        data = {
            "msgtype": "text",
            "text": {
                "content": f"告警机器人：{message}",
            }
        }

        sendData = json.dumps(data)
        t = requests.post(url=webhook, data=sendData, headers=headers)
        content = t.content.decode()
        print(datetime.datetime.now(), end=' ')
        print(content)
        if t.json()["errcode"] == 0:
            return True
        else:
            return False


def list_str(list):
    # 数据转换，list转换为str字符串
    str_list = []
    for i in range(len(list)):
        message = "项目名称：" + list[i][0] + ",到期时间：" + list[i][1] + "，距离到期时间剩余天数是：" + str(list[i][2]) + "天。"
        str_list.append(message)
    return dingtalk_warning(str_list)


def computing_time():
    # 链接数据库信息
    db = pymysql.connect(host="192.168.1.222",
                         port=3306,
                         user="root",
                         password="123456",
                         database="it_message",
                         charset="utf8"
                         )
    # 创建游标
    cursor = db.cursor()

    # 得到系统过的过期日期和告警日期
    sql_sys_end_time = 'SELECT  sys_end_time, reminder_time, sys_desc  from it_message.it_message_time '
    cursor.execute(sql_sys_end_time)
    results_time = cursor.fetchall()
    # print(results_time)
    sys_list = []
    for day1,day2,sys_desc in results_time:
        """
        day1 是数据库中截至时间，取到的日期是<class 'datetime.date'>类型，需要转换为 str类型
        day2 是数据库中到期前提醒的日期
        sys_desc 是描述信息
        """
        d1 = day1
        d2 = datetime.date.today()
        # d1 = datetime.datetime.strptime(day1.strftime('%Y-%m-%d'), '%Y-%m-%d')
        # d2 = datetime.datetime.strptime(datetime.date.today().strftime('%Y-%m-%d'), '%Y-%m-%d')
        d3 = d1 - d2
        if 0 < d3.days <=  day2:
            sys_list.append([sys_desc, day1.strftime('%Y-%m-%d'), d3.days])
    db.close()
    return list_str(sys_list)



if __name__ == '__main__':
    computing_time()